package com.jfl.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 登出过滤器
 * 
 * @author 赵炎
 * @version [V1.00, 2018年12月5日]
 * @since V1.00
 */
public class LogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter
{
    private static final Logger LOG = LoggerFactory.getLogger(LogoutFilter.class);
    
    /**
     * 退出后重定向的地址
     */
    private String loginUrl;
    
    public String getLoginUrl()
    {
        return loginUrl;
    }
    
    public void setLoginUrl(String loginUrl)
    {
        this.loginUrl = loginUrl;
    }
    
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception
    {
        try
        {
            Subject subject = getSubject(request, response);
            String redirectUrl = getRedirectUrl(request, response, subject);
            try
            {
                // 退出登录
                subject.logout();
            }
            catch (SessionException e)
            {
                LOG.error("logout fail.", e);
            }
            issueRedirect(request, response, redirectUrl);
        }
        catch (Exception e)
        {
            LOG.error("logout error.", e);
        }
        // 不执行后续的过滤器，直接返回跳转到登录页面
        return false;
    }
    
    /**
     * 退出跳转URL
     * @param request
     * @param response
     * @param subject
     * @return
     * @see org.apache.shiro.web.filter.authc.LogoutFilter#getRedirectUrl(javax.servlet.ServletRequest, javax.servlet.ServletResponse, org.apache.shiro.subject.Subject)
     */
    @Override
    protected String getRedirectUrl(ServletRequest request, ServletResponse response, Subject subject)
    {
        String url = getLoginUrl();
        if (StringUtils.isNotEmpty(url))
        {
            return url;
        }
        return super.getRedirectUrl(request, response, subject);
    }
}
